//-----------------------------------------------------------------------------
// File: AppUiService.cs
//
// Copyright (c) Dmitry Shuklin. All rights reserved.
//-----------------------------------------------------------------------------
using System;

namespace ObjectiveDraw.Platform
{
	/// <summary>
	/// Summary description for Class1.
	/// </summary>
	public class AppUiService : Cerebrum.Windows.Forms.Reflection.UiServiceDescriptor 
	{
		public AppUiService()
		{
			//
			// TODO: Add constructor logic here
			//
		}

		public override bool CommandActivated(Cerebrum.IConnector message, object sender, object argument)
		{
			string name = ((Cerebrum.Reflection.MessageDescriptor)message.Component).Name;

			switch(name)
			{
				case "Init":
				{
					Cerebrum.ObjectHandle appHnd = Cerebrum.Management.Utilites.ResolveHandle(this.DomainContext, "Components", "Name", ObjectiveDraw.Platform.Application.SystemComponentId);
					using(Cerebrum.IComposite connectorApp = this.DomainContext.AttachConnector(appHnd))
					{
						ObjectiveDraw.Platform.Serialization.FallbackChain chainApp = new ObjectiveDraw.Platform.Serialization.FallbackChain(null, connectorApp as Cerebrum.IContainer);
						SerializationContext sc = new SerializationContext(null, Cerebrum.SerializeDirection.Load, new System.Collections.Hashtable());
						
						ObjectiveDraw.Platform.Application ta = (ObjectiveDraw.Platform.Application)Workspace.CreateInstanceByTypeName(this.DomainContext, ObjectiveDraw.Platform.Application.SystemComponentId, this.DomainContext, appHnd, chainApp, sc);
						this.DomainContext.Properties[ObjectiveDraw.Platform.Application.m_ApplicationProperty] = ta;

						Cerebrum.Windows.Forms.Application ca = this.DomainContext.Application as Cerebrum.Windows.Forms.Application;
						ta.PrimaryWindow = (Cerebrum.DesktopEngine.PrimaryWindowForm)ca.PrimaryWindow;
					}
					return true;
				}
				case "ResetOptions1":
				{
					/*DebugTraceForm.ShowWindow();
					Cerebrum.Integrator.DomainContext c = (Cerebrum.Integrator.DomainContext)Cerebrum.Windows.Forms.Application.Instance.OpenedDomains[0];
					Cerebrum.DesktopEngine.EmergencyConfigurator dlg = new Cerebrum.DesktopEngine.EmergencyConfigurator();
					((Cerebrum.IComponent)dlg).SetConnector(Cerebrum.SerializeDirection.None, new Cerebrum.Runtime.SurrogateComposite(c.Workspace));
					dlg.Show();*/

					ObjectiveDraw.Platform.Application application = this.DrawerApplication;

					/* - do NOT delete */

					ObjectiveDraw.Platform.IDrawerComponent component = application; //application.m_ActiveWorkspace;

					System.Drawing.Color c = System.Drawing.Color.WhiteSmoke;
					Serialization.TypeSerializer.SetValue(component, KnownDrawerVariables.GraphBackgroundColor, false, System.Drawing.SystemColors.Control); //c); //
					Serialization.TypeSerializer.SetValue(component, KnownDrawerVariables.SplitterBackgroundColor, false, c);
					Serialization.TypeSerializer.SetValue(component, KnownDrawerVariables.SplitterThicknessInteger, false, 4);
					Serialization.TypeSerializer.SetValue(component, KnownDrawerVariables.ChartBackgroundColor, false, System.Drawing.Color.FromArgb(128, System.Drawing.Color.White));
					//Serialization.TypeSerializer.SetValue(component, KnownDrawerVariables.ToolBarButtonEnterFillColor, false, System.Drawing.Color.DodgerBlue);
					Serialization.TypeSerializer.SetValue(component, KnownDrawerVariables.ToolBarButtonEnterRectColor, false, System.Drawing.Color.Navy);
					//Serialization.TypeSerializer.SetValue(component, KnownDrawerVariables.ToolBarButtonCheckFillColor, false, System.Drawing.Color.Gold);
					Serialization.TypeSerializer.SetValue(component, KnownDrawerVariables.ToolBarButtonCheckRectColor, false, System.Drawing.Color.Coral);
					//Serialization.TypeSerializer.SetValue(component, KnownDrawerVariables.ToolBarButtonPressFillColor, false, System.Drawing.Color.LightCoral);
					Serialization.TypeSerializer.SetValue(component, KnownDrawerVariables.ToolBarButtonPressRectColor, false, System.Drawing.Color.DarkRed);
					Serialization.TypeSerializer.SetValue(component, KnownDrawerVariables.ChartOrdinateTenColor, false, System.Drawing.Color.FromArgb((int)(c.R * 0.7f), (int)(c.G * 0.7f), (int)(c.B * 0.7f)));
					Serialization.TypeSerializer.SetValue(component, KnownDrawerVariables.ChartOrdinateFiveColor, false, System.Drawing.Color.FromArgb((int)(c.R * 0.8f), (int)(c.G * 0.8f), (int)(c.B * 0.8f)));
					Serialization.TypeSerializer.SetValue(component, KnownDrawerVariables.ChartOrdinateOneColor, false, System.Drawing.Color.FromArgb((int)(c.R * 0.9f), (int)(c.G * 0.9f), (int)(c.B * 0.9f)));
					Serialization.TypeSerializer.SetValue(component, KnownDrawerVariables.ChartHorizontalStrideColor, false, System.Drawing.Color.FromArgb((int)(c.R * 0.8f), (int)(c.G * 0.8f), (int)(c.B * 0.8f)));
					Serialization.TypeSerializer.SetValue(component, KnownDrawerVariables.ChartHorizontalDatumColor, false, System.Drawing.Color.FromArgb((int)(c.R * 0.5f), (int)(c.G * 0.5f), (int)(c.B * 0.5f)));
				
					Serialization.TypeSerializer.SetValue(component, KnownDrawerVariables.ToolTipMessageFillColor, false, System.Drawing.Color.FromArgb(196, System.Drawing.Color.Yellow));
					Serialization.TypeSerializer.SetValue(component, KnownDrawerVariables.ToolTipMessageRectColor, false, System.Drawing.Color.Gold);
					Serialization.TypeSerializer.SetValue(component, KnownDrawerVariables.ToolTipMessageForeColor, false, System.Drawing.Color.DarkRed);

					c = System.Drawing.Color.DimGray;
					Serialization.TypeSerializer.SetValue(component, KnownDrawerVariables.RulerOrdinateTenColor, false, System.Drawing.Color.FromArgb((int)(c.R * 0.7f), (int)(c.G * 0.7f), (int)(c.B * 0.7f)));
					Serialization.TypeSerializer.SetValue(component, KnownDrawerVariables.RulerOrdinateFiveColor, false, System.Drawing.Color.FromArgb((int)(c.R * 0.8f), (int)(c.G * 0.8f), (int)(c.B * 0.8f)));
					Serialization.TypeSerializer.SetValue(component, KnownDrawerVariables.RulerOrdinateOneColor, false, System.Drawing.Color.FromArgb((int)(c.R * 0.9f), (int)(c.G * 0.9f), (int)(c.B * 0.9f)));
					Serialization.TypeSerializer.SetValue(component, KnownDrawerVariables.RulerOrdinateTextColor, false, System.Drawing.Color.Blue);

					Serialization.TypeSerializer.SetValue(component, KnownDrawerVariables.RulerHorizontalStrideColor, false, System.Drawing.Color.FromArgb((int)(c.R * 0.8f), (int)(c.G * 0.8f), (int)(c.B * 0.8f)));
					Serialization.TypeSerializer.SetValue(component, KnownDrawerVariables.RulerHorizontalDatumColor, false, System.Drawing.Color.FromArgb((int)(c.R * 0.7f), (int)(c.G * 0.7f), (int)(c.B * 0.7f)));
					Serialization.TypeSerializer.SetValue(component, KnownDrawerVariables.RulerHorizontalTextColor, false, System.Drawing.Color.Blue);

					Serialization.TypeSerializer.SetValue(component, KnownDrawerVariables.ShapeForegroundColor, false, System.Drawing.Color.Black);
					Serialization.TypeSerializer.SetValue(component, KnownDrawerVariables.ShapeManipulatorColor, false, System.Drawing.Color.DimGray);
					Serialization.TypeSerializer.SetValue(component, KnownDrawerVariables.ShapeControlPrimaryColor, false, System.Drawing.Color.DimGray);
					Serialization.TypeSerializer.SetValue(component, KnownDrawerVariables.ShapeControlServiceColor, false, System.Drawing.Color.Red);
					Serialization.TypeSerializer.SetValue(component, KnownDrawerVariables.ShapeControlPrimaryColor, false, System.Drawing.Color.DarkBlue);

					return true;
				}
				case KnownDrawerCommands.NewDatabase:
				{
					CreateDocument();
					return true;
				}
				case KnownDrawerCommands.NewWorksheet:
				{
					Cerebrum.Windows.Forms.Application _fa = this.DomainContext.Application as Cerebrum.Windows.Forms.Application;
					ObjectiveDraw.Platform.Application _ta = this.DrawerApplication;

					ObjectiveDraw.Platform.DrawerDocument c = null;
					c = _ta.ActiveDocument;
					if(c!=null)
					{
						SerializationContext context = new SerializationContext(c, Cerebrum.SerializeDirection.Init, new System.Collections.Hashtable());
						ObjectiveDraw.Platform.GraphChartDevice dev1 = (ObjectiveDraw.Platform.GraphChartDevice)Workspace.InitializeInstance(c, ObjectiveDraw.Platform.GraphChartDevice.SystemComponentId, context);
						((Cerebrum.IComponent)dev1).SetConnector(Cerebrum.SerializeDirection.Init, new Cerebrum.Runtime.SurrogateComposite(c.Workspace));
						c.DrawerApplication.ApplicationTimer += new EventHandler(dev1.OnApplicationTimer);
						dev1.InitVariables();
						dev1.ReCreateRenderTarget(Cerebrum.Windows.Forms.DesktopComponentDisposition.Child);

						dev1.AddNewChart(true);
						c.m_Windows.Add(dev1);
					}
					return true;
				}
				case KnownDrawerCommands.CloseDatabase:
				{
					CloseActiveDocument(this.DrawerApplication);
					return true;
				}
				case KnownDrawerCommands.ConfigurationExport:
				{
					Cerebrum.Windows.Forms.Application _fa = this.DomainContext.Application as Cerebrum.Windows.Forms.Application;
					ObjectiveDraw.Platform.Application _ta = this.DrawerApplication;

					System.Windows.Forms.SaveFileDialog dlg = new System.Windows.Forms.SaveFileDialog();
					dlg.Filter = "Objective Draw Application Configuration file (*.xcfg)|*.xcfg";
					dlg.DefaultExt = "xcfg";
					if(dlg.ShowDialog(_fa.PrimaryWindow)==System.Windows.Forms.DialogResult.OK)
					{
						using(System.IO.Stream fs = dlg.OpenFile())
						{
							System.Xml.XmlTextWriter xw = new System.Xml.XmlTextWriter(fs, System.Text.Encoding.Default);

							xw.Formatting = System.Xml.Formatting.Indented;

							xw.WriteStartDocument(false);
							xw.WriteDocType("vnpidb", null, null/*"vnpiodl.dtd"*/, null);
							xw.WriteStartElement("ObjectiveDrawAppConfig");

							System.ComponentModel.PropertyDescriptorCollection pds = ObjectiveDraw.Platform.Serialization.TypeSerializer.GetSerializer(_ta.GetType()).GetProperties();
							foreach(System.ComponentModel.PropertyDescriptor itemPrp in pds)
							{
								object o = itemPrp.GetValue(_ta);
								if (o != null && o != System.DBNull.Value)
								{
									if (o.GetType() == typeof(Cerebrum.ObjectHandle))
									{
										Cerebrum.ObjectHandle h = Cerebrum.ObjectHandle.Null;
										h = (Cerebrum.ObjectHandle)o;

										xw.WriteStartElement("value");
										xw.WriteAttributeString("name", itemPrp.Name);
										xw.WriteAttributeString("type", "Cerebrum.ObjectHandle");
										xw.WriteString(Convert.ToString(h));
										xw.WriteEndElement();
									}
									else if (o.GetType() == typeof(System.Int32))
									{
										System.Int32 v = 0;
										v = Convert.ToInt32(o);

										xw.WriteStartElement("value");
										xw.WriteAttributeString("name", itemPrp.Name);
										xw.WriteAttributeString("type", "System.Int32");
										xw.WriteString(Convert.ToString(v));
										xw.WriteEndElement();
									}
									else if (o.GetType() == typeof(System.Drawing.Color))
									{
										System.Drawing.Color v;
										v = (System.Drawing.Color)o;

										xw.WriteStartElement("value");
										xw.WriteAttributeString("name", itemPrp.Name);
										xw.WriteAttributeString("type", "System.Drawing.Color");
										xw.WriteString("#" + v.ToArgb().ToString("x").PadLeft(8, '0'));
										xw.WriteEndElement();
									}
									else// if (itemPrp.PropertyType == typeof(System.Object))
									{
										using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
										{
											System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
											formatter.Serialize(ms, o);
											xw.WriteStartElement("value");
											xw.WriteAttributeString("name", itemPrp.Name);
											xw.WriteAttributeString("type", "System.Object");
											xw.WriteString(Convert.ToBase64String(ms.ToArray()));
											xw.WriteEndElement();
										}
									}
								}/*
								else
								{
									object o = itemPrp.GetValue(_ta);
									if (o != null && !Convert.IsDBNull(o))
									{
										xw.WriteStartElement("value");
										xw.WriteAttributeString("name", itemPrp.Name);
										xw.WriteString(Convert.ToString(o));
										xw.WriteEndElement();
									}
								}*/
							}

							xw.WriteEndElement();
							xw.WriteEndDocument();

							xw.Flush();
							fs.Flush();
							xw.Close();

							fs.Close();
						}
					}
					return true;
				}
				case KnownDrawerCommands.ConfigurationImport:
				{
					Cerebrum.Windows.Forms.Application _fa = this.DomainContext.Application as Cerebrum.Windows.Forms.Application;
					ObjectiveDraw.Platform.Application _ta = this.DrawerApplication;

					System.Windows.Forms.OpenFileDialog dlg = new System.Windows.Forms.OpenFileDialog();
					dlg.Filter = "Objective Draw Application Configuration file (*.xcfg)|*.xcfg";
					dlg.DefaultExt = "xcfg";
					if(dlg.ShowDialog(_fa.PrimaryWindow)==System.Windows.Forms.DialogResult.OK)
					{
						System.Xml.XmlDocument xdoc = null;

						using(System.IO.Stream fs = dlg.OpenFile())
						{
							System.IO.StreamReader sr = new System.IO.StreamReader(fs, System.Text.Encoding.Default);
							System.Xml.XmlTextReader xr = new System.Xml.XmlTextReader(sr);

							xdoc = new System.Xml.XmlDocument();
							xdoc.Load(xr);

							xr.Close();
							sr.Close();
							fs.Close();
						}

						System.ComponentModel.PropertyDescriptorCollection pds = ObjectiveDraw.Platform.Serialization.TypeSerializer.GetSerializer(_ta.GetType()).GetProperties();
						System.Xml.XmlNodeList xlist = xdoc.SelectNodes("ObjectiveDrawAppConfig/value");
						foreach(System.Xml.XmlNode xnode in xlist)
						{
							System.Xml.XmlAttribute xname = xnode.Attributes["name"];
							System.Xml.XmlAttribute xtype = xnode.Attributes["type"];
							string sname = xname==null?string.Empty:xname.Value;
							string stype = xtype==null?string.Empty:xtype.Value;
							string svalue = xnode.InnerText;
							System.ComponentModel.PropertyDescriptor itemPrp = pds[sname];
							if(itemPrp!=null)
							{
								object o = null;
								if(stype == "Cerebrum.ObjectHandle")
								{
									o = Cerebrum.ObjectHandle.Parse(svalue);
								}
								else if(stype == "System.Int32")
								{
									o = System.Int32.Parse(svalue);
								}
								else if(stype == "System.Drawing.Color")
								{
									string s = svalue[0]=='#'?svalue.Substring(1):svalue;
									int v = System.Int32.Parse(s, System.Globalization.NumberStyles.HexNumber);
									o = System.Drawing.Color.FromArgb(v);
								}
								else //if(stype == "System.Object")
								{
									using(System.IO.MemoryStream ms = new System.IO.MemoryStream(Convert.FromBase64String(svalue)))
									{
										System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
										o = formatter.Deserialize(ms);
									}
								}
								itemPrp.SetValue(_ta, o);
							}
						}

						SerializationContext sc = new SerializationContext(_ta, Cerebrum.SerializeDirection.Save, new System.Collections.Hashtable());
						using(Cerebrum.IComposite connectorApp = _ta.DomainContext.AttachConnector(_ta.ObjectHandle))
						{
							ObjectiveDraw.Platform.Serialization.FallbackChain chainApp = new ObjectiveDraw.Platform.Serialization.FallbackChain(null, connectorApp as Cerebrum.IContainer);
							_ta.Serialize(chainApp, sc);
						}
					}
					return true;
				}
				case KnownDrawerCommands.ApplicationOptions:
				{
					Workspace.ConfigureComponent(this.DrawerApplication, KnownDrawerCommands.ConfigurationUpdate, null);
					return true;
				}
				case "Open":
				{
					Cerebrum.Windows.Forms.Application application = this.DomainContext.Application as Cerebrum.Windows.Forms.Application;
					ObjectiveDraw.Platform.DrawerDocument c = null;
					if(argument is Cerebrum.Integrator.DomainContextEventArgs)
					{
						c = (argument as Cerebrum.Integrator.DomainContextEventArgs).DomainContext as ObjectiveDraw.Platform.DrawerDocument;
					}
					else
					{
						string fileName = string.Empty;
						int mode = -1;
						if(argument is Cerebrum.Windows.Forms.FileNameEventArgs)
						{
							fileName = (argument as Cerebrum.Windows.Forms.FileNameEventArgs).FileName;
						}
						else
						{
							System.Windows.Forms.OpenFileDialog dlg = new System.Windows.Forms.OpenFileDialog();
							dlg.DefaultExt = "exp";
							dlg.Filter = "Objective Draw files|*.vnn|Expert Source files|*.exp|All files|*.*";
							if(dlg.ShowDialog(application.PrimaryWindow)==System.Windows.Forms.DialogResult.OK)
							{
								fileName = dlg.FileName;
								if(dlg.FilterIndex > 0 && dlg.FilterIndex < 3)
								{
									mode = dlg.FilterIndex - 1;
								}
							}
						}
						if(mode < 0)
						{
							string ext = System.IO.Path.GetExtension(fileName).ToLower();
							if(ext==".exp")
							{
								mode = 1;
							}
							if(ext==".vnn")
							{
								mode = 0;
							}
						}
						if(mode==1)
						{
							//OpenSource(fileName);
						}
						if(mode==0)
						{
							Cerebrum.Integrator.IContextService lcs = new Cerebrum.Management.SimpleContextService(application, fileName, null, 4, true, "", false);
							Cerebrum.IWorkspace domain = lcs.LoadContext(fileName);
							c = domain.Component as ObjectiveDraw.Platform.DrawerDocument;
							application.AddDomain(c);
						}
					}
				
					if(c!=null)
					{
						c.Workspace.Activator = this.DrawerApplication.ObjectActivator;
						ObjectiveDraw.Platform.Application _ta = this.DrawerApplication;
						c.OwnerComponent = _ta;
						CloseActiveDocument(_ta);
						_ta.ActiveDocument = c;

						OpenDocument(c);
					}
					return true;
				}
				case "ObjectiveDraw.About":
				{
					try
					{
						Cerebrum.Windows.Forms.Application application = this.DomainContext.Application as Cerebrum.Windows.Forms.Application;
						ObjectiveDraw.Platform.Information.AboutForm dlg = new ObjectiveDraw.Platform.Information.AboutForm();
						ObjectiveDraw.Platform.Information.AboutDevice dev = new ObjectiveDraw.Platform.Information.AboutDevice();
						dev.RenderTarget = dlg.DirectControl;
						((Cerebrum.IComponent)dev).SetConnector(Cerebrum.SerializeDirection.None, new Cerebrum.Runtime.SurrogateComposite(this.m_Connector.Workspace));
						dlg.ShowDialog(application.PrimaryWindow);
					}
					catch
					{
						Cerebrum.Windows.Forms.Application application = this.DomainContext.Application as Cerebrum.Windows.Forms.Application;
						ObjectiveDraw.Platform.Information.AboutFormWinForms dlg = new ObjectiveDraw.Platform.Information.AboutFormWinForms();
						dlg.ShowDialog(application.PrimaryWindow);
					}
					return true;
				}
				case "ObjectiveDraw.Credits":
				{
					Cerebrum.Windows.Forms.Application application = this.DomainContext.Application as Cerebrum.Windows.Forms.Application;
					ObjectiveDraw.Platform.Information.CreditsForm dlg = new ObjectiveDraw.Platform.Information.CreditsForm();
					ObjectiveDraw.Platform.Information.CreditsDevice dev = new ObjectiveDraw.Platform.Information.CreditsDevice();
					dev.RenderTarget = dlg;
					((Cerebrum.IComponent)dev).SetConnector(Cerebrum.SerializeDirection.None, new Cerebrum.Runtime.SurrogateComposite(this.m_Connector.Workspace));
					dlg.ShowDialog(application.PrimaryWindow);
					return true;
				}

			}
			return base.CommandActivated(message, sender, argument);
		}

		private static void CloseActiveDocument(ObjectiveDraw.Platform.Application _ta)
		{
			ObjectiveDraw.Platform.DrawerDocument d = _ta.ActiveDocument;
			if(d!=null)
			{
				SerializationContext sc = new SerializationContext(_ta, Cerebrum.SerializeDirection.Save, new System.Collections.Hashtable());
				using(Cerebrum.IComposite connectorApp = _ta.DomainContext.AttachConnector(_ta.ObjectHandle))
				{
					ObjectiveDraw.Platform.Serialization.FallbackChain chainApp = new ObjectiveDraw.Platform.Serialization.FallbackChain(null, connectorApp as Cerebrum.IContainer);

					using(Cerebrum.IComposite connector = d.AttachConnector(d.ObjectHandle))
					{
						d.Serialize(chainApp.CreateDependent(connector as Cerebrum.IContainer), sc);
					}
				}

				d.Shutdown();
			}
		}

		/*public override void ComponentActivated(object component)
		{
			base.ComponentActivated (component);

			Cerebrum.Windows.Forms.IUiControl cmdCompile = Cerebrum.Windows.Forms.Application.Instance.PrimaryWindow.GetCommand("Compile");
			Cerebrum.Windows.Forms.IUiControl cmdCalculate = Cerebrum.Windows.Forms.Application.Instance.PrimaryWindow.GetCommand("Calculate");

			if(component is SourceEditor)
			{
				cmdCompile.Enabled = true;
				cmdCalculate.Enabled = false;
			}
			else if(component is ElexDatabase)
			{
				cmdCompile.Enabled = false;
				cmdCalculate.Enabled = true;
			}
			else
			{
				cmdCompile.Enabled = false;
				cmdCalculate.Enabled = false;
			}
		}*/

		public void CreateDocument()
		{
			Cerebrum.Windows.Forms.Application application = this.DomainContext.Application as Cerebrum.Windows.Forms.Application;
			Cerebrum.Windows.Forms.CreateDatabase dlg = new Cerebrum.Windows.Forms.CreateDatabase(Cerebrum.Windows.Forms.CreateDatabaseOptions.None);
			dlg.DomainName = ObjectiveDraw.Platform.DrawerDocument.SystemName;
			dlg.ClusterFrameSize = 4;
			dlg.Versioning = true;
			if(dlg.ShowDialog(application.PrimaryWindow)==System.Windows.Forms.DialogResult.OK)
			{
				string bcfg = System.IO.Path.Combine(application.ApplicationDirectory, @"ObjectiveDraw\Import\ObjectiveDraw.Database.xdb");
				
				Cerebrum.Integrator.IContextService lcs = new Cerebrum.DesktopEngine.SmartContextService(application, dlg.ClusterFileName, null, dlg.ClusterFrameSize, dlg.Versioning, bcfg, true);
				((Cerebrum.IComponent)lcs).SetConnector(Cerebrum.SerializeDirection.None, new Cerebrum.Runtime.SurrogateComposite(application.MasterContext.Workspace));
						
				//lcs.InitContextDebug(c);
				Cerebrum.IWorkspace domain = lcs.InitContext(dlg.ClusterFileName, dlg.DomainName);
				domain.Activator = this.DrawerApplication.ObjectActivator;
				ObjectiveDraw.Platform.DrawerDocument c = domain.Component as ObjectiveDraw.Platform.DrawerDocument;
				c.OwnerComponent = this.DrawerApplication;
				application.AddDomain(c);

				lcs.ImportDatabase(c, true);
				

				this.DrawerApplication.ActiveDocument = c;

				using(Cerebrum.Data.TableView view = Cerebrum.Management.Utilites.GetView(c, "Components"))
				{
					Cerebrum.Data.ComponentItemView item = view.AddNew();
					item["Name"] = ObjectiveDraw.Platform.DrawerDocument.SystemName;
					c.ObjectHandle = item.ObjectHandle;









					//DebugTraceForm.ShowWindow();
					SerializationContext context = new SerializationContext(c, Cerebrum.SerializeDirection.Init, new System.Collections.Hashtable());
					ObjectiveDraw.Platform.GraphChartDevice dev1 = (ObjectiveDraw.Platform.GraphChartDevice)Workspace.InitializeInstance(c, ObjectiveDraw.Platform.GraphChartDevice.SystemComponentId, context);
					((Cerebrum.IComponent)dev1).SetConnector(Cerebrum.SerializeDirection.Init, new Cerebrum.Runtime.SurrogateComposite(c.Workspace));
					c.DrawerApplication.ApplicationTimer += new EventHandler(dev1.OnApplicationTimer);
					dev1.InitVariables();
					dev1.ReCreateRenderTarget(Cerebrum.Windows.Forms.DesktopComponentDisposition.Child);

					/*WorksheetChart chart = new WorksheetChart();
							((Cerebrum.Runtime.IComponent)chart).SetConnector(Cerebrum.Runtime.SerializeDirection.Init, new Cerebrum.Runtime.SurrogateComposite(c.Workspace));
							chart.InitVariables();
		warning "hardcoded"
							chart.SetBarDrawer(System.Activator.CreateInstance(typeof(ZBarDrawer)) as DrawerBarDrawerBase);
							chart.ConstructConditions(true);
							dev1.AddChart(chart, false, true);
							dev1.m_AbscissaScroller.TimeBase = new ReferenceTimeStride();*/

					dev1.AddNewChart(true);
					c.m_Windows.Add(dev1);




					//System.Diagnostics.Trace.WriteLine("t1 = " + System.DateTime.Now.ToString());

					SerializationContext sc = new SerializationContext(null, Cerebrum.SerializeDirection.Save, new System.Collections.Hashtable());
					using(Cerebrum.IComposite connector = item.GetComposite())
					{
						c.Serialize(new ObjectiveDraw.Platform.Serialization.FallbackChain(null, connector as Cerebrum.IContainer), sc);
					}
					//System.Diagnostics.Trace.WriteLine("t2 = " + System.DateTime.Now.ToString());
				}
			}
		}

		private void OpenDocument(ObjectiveDraw.Platform.DrawerDocument c)
		{
			//DebugTraceForm.ShowWindow();

			//System.Diagnostics.Trace.WriteLine("t1 = " + System.DateTime.Now.ToString());

			c.ObjectHandle = Cerebrum.Management.Utilites.ResolveHandle(c, "Components" ,"Name", ObjectiveDraw.Platform.DrawerDocument.SystemName);
			
			using(Cerebrum.IComposite connectorApp = this.DrawerApplication.DomainContext.AttachConnector(this.DrawerApplication.ObjectHandle))
			{
				ObjectiveDraw.Platform.Serialization.FallbackChain chainApp = new ObjectiveDraw.Platform.Serialization.FallbackChain(null, connectorApp as Cerebrum.IContainer);
				SerializationContext sc = new SerializationContext(this.DrawerApplication, Cerebrum.SerializeDirection.Load, new System.Collections.Hashtable());
				using(Cerebrum.IComposite connector = c.AttachConnector(c.ObjectHandle))
				{
					c.Serialize(new ObjectiveDraw.Platform.Serialization.FallbackChain(chainApp, connector as Cerebrum.IContainer), sc);
				}
			}
			//System.Diagnostics.Trace.WriteLine("t2 = " + System.DateTime.Now.ToString());
		}

		public ObjectiveDraw.Platform.Application DrawerApplication
		{
			get
			{
				return this.DomainContext.Properties[ObjectiveDraw.Platform.Application.m_ApplicationProperty] as ObjectiveDraw.Platform.Application;
			}
		}

	}
}
